package com.lfg.leetcode.leetcode0;

public class No23MergeKLists {
    public static ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        if (lists.length == 1) {
            return lists[0];
        }
        return mergeKLists(lists, 0, lists.length - 1);
    }

    public static ListNode mergeKLists(ListNode[] lists, int sIndex, int eIndex) {
        if (sIndex == eIndex) {
            return lists[sIndex];
        }
        if (sIndex == eIndex - 1) {
            return mergeTwoLists(lists[sIndex], lists[eIndex]);
        }
        int middle = (sIndex + eIndex) / 2;
        if (sIndex < eIndex) {
            ListNode l1 = mergeKLists(lists, sIndex, middle);
            ListNode l2 = mergeKLists(lists, middle + 1, eIndex);
            return mergeTwoLists(l1, l2);
        }

        return null;
    }


    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode ret = new ListNode(1);
        ListNode node = ret;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                node.next = l1;
                node = node.next;
                l1 = l1.next;
            } else {
                node.next = l2;
                node = node.next;
                l2 = l2.next;
            }

        }
        if (null != l1) {
            node.next = l1;
        }
        if (null != l2) {
            node.next = l2;
        }
        return ret.next;
    }

    public static void main(String[] args) {
        System.out.println(mergeKLists(new ListNode[]{ListNode.deserialize("[1,2,3,4]"), ListNode.deserialize("[1,2,3,5]"), ListNode.deserialize("[1,3,3]")}).val);
//        System.out.println(threeSum(new int[]{-2,0,0,2,2}));
    }
}
